<template>
	<view class="exam-content">
		<block v-if="currentQuestion.kind">
		<view class="u-line"></view>
		<!-- 进度与题型 -->
		<view class="question-info">
			<text class="question-type">{{ currentQuestion.kind | typeFilter }}</text>
			<text class="question-progress">{{ currentIndex + 1 }}/{{ questions.length }}</text>
		</view>

		<!-- 题目内容 -->
		<view class="question-content">
			<rich-text :nodes="currentQuestion.title"></rich-text>
		</view>

		<!-- 选项区域 -->
		<view class="options">

			<!-- 判断题 -->
			<template v-if="currentQuestion.kind === 'JUDGE'">
				<view v-for="(option, index) in currentQuestion.options_json" :key="index" class="option-item multiple"
					:class="option.click_index && currentQuestion.answer === option.key?'active':(option.click_index && currentQuestion.answer !== option.key?'error':'')"
					@click="handleJudge(option,index)">
					{{ option.key }}. {{ option.value }}
					<text v-if="option.click_index && currentQuestion.answer === option.key" class="checkmark">✓</text>
					<text v-if="option.click_index && currentQuestion.answer !== option.key"
						class="checkmark error">✘</text>
				</view>
			</template>

			<!-- 单选题 -->
			<template v-if="currentQuestion.kind === 'SINGLE'">
				<view v-for="(option, index) in currentQuestion.options_json" :key="index" class="option-item multiple"
					:class="option.click_index && currentQuestion.answer === option.key?'active':(option.click_index && currentQuestion.answer !== option.key?'error':'')"
					@click="handleSingle(option,index)">
					{{ option.key }}. {{ option.value }}
					<text v-if="option.click_index && currentQuestion.answer === option.key" class="checkmark">✓</text>
					<text v-if="option.click_index && currentQuestion.answer !== option.key"
						class="checkmark error">✘</text>
				</view>
			</template>

			<!-- 多选题 -->
			<template v-if="currentQuestion.kind === 'MULTI'">
				<view v-for="(option, index) in currentQuestion.options_json" :key="index" class="option-item multiple"
					:class="currentAnswer.includes(index) && currentQuestion.answer.includes(option.key)?'active':(currentAnswer.includes(index) && !currentQuestion.answer.includes(option.key)?'error':'')"
					@click="handleMultiple(option,index)">
					{{ option.key }}. {{ option.value }}
					<text v-if="currentAnswer.includes(index) && currentQuestion.answer.includes(option.key)"
						class="checkmark">✓</text>
					<text v-if="currentAnswer.includes(index) && !currentQuestion.answer.includes(option.key)"
						class="checkmark error">✘</text>
				</view>
			</template>
		</view>
		<block v-if="currentQuestion.is_click">
			<view class="answer-info">
				<text class="question-type">正确答案</text>
				<text class="answer">{{ currentQuestion.answer}}</text>
			</view>
			<view class="u-line"></view>
			<view class="">
				<text class="text-bold">答案解析：</text>
				<view class="jx">
					<rich-text :nodes="currentQuestion.explain"></rich-text>
				</view>
			</view>
		</block>
		<view class="fix-bottom">
			<u-grid :border="false" @click="clickMenu" col="4">
				<u-grid-item>
					<u-icon :customStyle="{paddingTop:20+'rpx'}" name="grid" :size="50"></u-icon>
					<text class="grid-text">{{ currentIndex + 1 }}/{{ questions.length }}</text>
				</u-grid-item>
				<u-grid-item>
					<u-icon :customStyle="{paddingTop:20+'rpx'}" name="play-left" :size="50"></u-icon>
					<text class="grid-text">上一题</text>
				</u-grid-item>
				<u-grid-item>
					<u-icon :customStyle="{paddingTop:20+'rpx'}" name="play-right" :size="50"></u-icon>
					<text class="grid-text">下一题</text>
				</u-grid-item>
				<u-grid-item>
					<u-icon :customStyle="{paddingTop:20+'rpx'}" name="file-text" :size="50"></u-icon>
					<text class="grid-text">结束练习</text>
				</u-grid-item>
			</u-grid>
		</view>
		</block>
		
		<!-- 空数据 -->
		<view class="fa-empty" v-if="!currentQuestion.kind">
			<u-empty textSize="28" mode="data"></u-empty>
		</view>
		<u-popup :show="tkShow" @close="tkShow=false">
			<view class="tm-list">
				<block v-for="(item,index) in quetionCard" :key="index">
					<view v-if="index == currentIndex" :class="index == currentIndex?'tm-xh active-xh':'tm-xh'" @click="choiceTopic(index)">
						{{index+1}}
					</view>
					<view v-else class="tm-xh"
						:class="item.answer_status=='success'?'success':(index !== currentIndex&&item.answer_status=='error'?'error':'')"
						@click="choiceTopic(index)">
						{{index+1}}
					</view>

				</block>
			</view>
		</u-popup>
		<u-popup :show="endShow" :round="20" mode="center" @close="endShow=false" :customStyle="{'width':'60%'}">
			<view class="tui-mode">
				<view class="title">结束练题</view>
				<view class="num">正确题数：<text class="text-green">{{successNum}}</text>题</view>
				<view class="num">错误题数：<text class="text-red">{{errorNum}}</text>题</view>
				<view class="num">未答题数：<text class="text-yellow">{{defaultNum}}</text>题</view>
				<view class="btn">
					<u-button shape="circle"
					:customStyle="{'background-color':theme.bgColor,'color':'#ffffff'}"
					 @click="endShow=false" text="确定退出" ></u-button>
					 <u-button shape="circle"
					 :customStyle="{'color':theme.bgColor,'margin-left':'30rpx'}"
					  @click="endShow=false" text="取消" ></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: 'fa-beiti',
		props: {
			questions: {
				type: Array,
				default: []
			},
			judgeOptions: {
				type: Array,
				default: []
			}
		},
		computed: {
			currentQuestion() {
				return this.questions[this.currentIndex]
			},
			currentAnswer: {
				get() {

					return this.userAnswers[this.currentIndex] ||
						(this.currentQuestion.kind === 'MULTI' ? [] : 0)
				},
				set(val) {
					this.$set(this.userAnswers, this.currentIndex, val)
				}
			},
		},

		data() {
			return {
				userAnswers: [],
				currentIndex: 0,
				timeRemaining: 3592,
				tkShow: false,
				answer: '',
				quetionCard: [],
				endShow:false,
				successNum:0,
				errorNum:0,
				defaultNum:0
			};
		},

		filters: {
			typeFilter(type) {
				const typeMap = {
					JUDGE: '判断题',
					SINGLE: '单选题',
					MULTI: '多选题'
				}
				return typeMap[type]
			}
		},
		methods: {
			clickMenu(e) {
				if (e === 0) {
					this.quetionCard = this.questions
					// console.log()
					this.tkShow = true
				}
				if (e === 1) {
					this.prevQuestion()
				}
				if (e === 2) {
					this.nextQuestion()
				}
				if (e === 3) {
					this.submitExam()
				}
			},
			choiceTopic(index) {
				this.currentIndex = index
				this.tkShow = false
			},
			// 处理判断题
			handleJudge(item, index) {
				if (this.currentQuestion.is_click) return;
				this.currentAnswer = index
				this.currentQuestion.is_click = true
				this.currentQuestion.options_json.map((item, index) => {
					item.click_index = false
				})
				item.click_index = true
				if (item.key === this.currentQuestion.answer) {
					this.currentQuestion.answer_status = 'success'
				} else {
					this.currentQuestion.answer_status = 'error'
				}
			},

			// 处理单选题
			handleSingle(item, index) {
				if (this.currentQuestion.is_click) return;
				this.currentAnswer = index
				this.currentQuestion.is_click = true
				this.currentQuestion.options_json.map((item, index) => {
					item.click_index = false
				})
				item.click_index = true
				if (item.key === this.currentQuestion.answer) {
					this.currentQuestion.answer_status = 'success'
				} else {
					this.currentQuestion.answer_status = 'error'
				}
			},

			// 处理多选题
			handleMultiple(item, index) {
				const selected = [...(this.currentAnswer || [])]
				const idx = selected.indexOf(index)
				// console.log('idx',idx)
				if (idx > -1) {
					// selected.splice(idx, 1)
				} else {
					selected.push(index)
				}
				item.click_index = true;
				if (!this.currentQuestion.answer.includes(item.key)) {
					this.currentQuestion.is_click = true
					this.currentQuestion.answer_status = 'error'
				}
				let selectIdx = [];
				this.currentQuestion.options_json.map((it, idx) => {
					if (it.click_index) {
						selectIdx.push(it.key)
					}
				})
				let sj = selectIdx.join(',')
				if (sj == this.currentQuestion.answer) {
					this.currentQuestion.is_click = true
					this.currentQuestion.answer_status = 'success'
				}
				this.currentAnswer = selected.sort((a, b) => a - b)
			},

			// 切换题目
			prevQuestion() {
				if (this.currentIndex > 0) {
					this.currentIndex--
				}
			},

			nextQuestion() {
				if (this.currentIndex < this.questions.length - 1) {
					this.currentIndex++
				}
			},

			// 提交考试
			submitExam() {
				// clearInterval(this.timer)

				// // 计算得分
				// let score = 0
				// console.log(this.questions)
				// this.questions.forEach((q, index) => {
				// 	const userAnswer = this.userAnswers[index]

				// 	if (q.link === 'MULTI') {
				// 		if (Array.isArray(userAnswer) &&
				// 			userAnswer.length === q.answer.length &&
				// 			userAnswer.every(v => q.answer.includes(v))) {
				// 			score++
				// 		}
				// 	} else {
				// 		if (userAnswer === q.answer) {
				// 			score++
				// 		}
				// 	}
					
				// })

				// uni.showModal({
				// 	title: '考试结果',
				// 	content: `得分：${score}/${this.questions.length}`,
				// 	showCancel: false,
				// 	success: () => {
				// 		// uni.navigateBack()
				// 	}
				// })
				this.successNum,this.errorNum,this.defaultNum=0;
				this.questions.map((item,index)=>{
					if(item.answer_status == 'success'){
						this.successNum++
					}
					if(item.answer_status == 'error'){
						this.errorNum++
					}
					if(item.answer_status == ''){
						this.defaultNum++
					}
				})
				this.endShow = true;
			},
			// 加载考试数据
			async loadExamData(id) {
				const res = await uni.request({
					url: `/api/exam/${id}`
				})
				this.questions = res.data.questions
				this.timeRemaining = res.data.duration * 60
			},

			// 增加答案保存逻辑
			saveProgress() {
				uni.setStorageSync('exam_progress', {
					answers: this.userAnswers,
					timestamp: Date.now()
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.exam-content {
		background-color: #ffffff;
		padding: 24rpx;
		.u-line{
			position: relative;
			width: 100%;
			height: 20rpx;
			background-color: #f6f6f6;
		}
	}

	.fix-bottom {
		bottom: calc(env(safe-area-inset-bottom) + 15px);
		width: 95%;
		position: fixed;
		margin: 0 auto;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding-bottom: 24rpx;

		.grid-text {
			font-size: 26rpx;
			color: #666666;
		}
	}


	.exam-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 0rpx;
		background-color: #ffffff;
		padding: 20rpx 0;

		.exam-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}

		.timer {

			text-align: center;
			font-size: 32rpx;
			color: #333333;
			font-weight: 600;

		}
	}

	.answer-info {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		margin-top: 30rpx;

		.question-type {
			// font-size: 28rpx;
			// color: #666;
			font-size: 24rpx;
			color: #fff;
			background: linear-gradient(135deg, #7892fd, #5677fc);
			padding: 8rpx 10rpx;
			border-radius: 14rpx 14rpx 14rpx 0;
			margin-right: 20rpx;
		}

		.answer {
			font-size: 28rpx;
			color: #007AFF;
		}
	}

	.question-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
		margin-top: 30rpx;

		.question-type {
			// font-size: 28rpx;
			// color: #666;
			font-size: 24rpx;
			color: #fff;
			background: linear-gradient(135deg, #7892fd, #5677fc);
			padding: 8rpx 10rpx;
			border-radius: 14rpx 14rpx 14rpx 0;
			margin-right: 20rpx;
		}

		.question-progress {
			font-size: 28rpx;
			color: #007AFF;
		}
	}

	.question-content {
		font-size: 32rpx;
		line-height: 1.6;
		margin-bottom: 50rpx;
		color: #333;
	}

	.options {
		.option-item {
			padding: 25rpx 30rpx;
			margin-bottom: 20rpx;
			background-color: #f6f6f6;
			border-radius: 12rpx;
			border: 1rpx solid #eee;
			position: relative;
			transition: all 0.2s;

			&.active {
				background-color: #e6f3ff;
				border-color: #007AFF;
				color: #007AFF;
			}

			&.error {
				background-color: rgba(255, 68, 0, .2);

			}

			&.multiple {
				padding-right: 80rpx;

				.checkmark {
					position: absolute;
					right: 30rpx;
					color: #007AFF;
					font-weight: bold;
				}

				.error {
					color: #f40f40;
				}
			}
		}
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin: 50rpx 0;

		button {
			flex: 0.48;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 30rpx;

			&[disabled] {
				background-color: #eee !important;
				color: #999 !important;
			}
		}

		.prev-btn {
			background-color: #f8f8f8;
			color: #666;
		}

		.next-btn {
			background-color: #007AFF;
			color: white;
		}
	}

	.tm-list {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		padding: 24rpx;

		.tm-xh {
			height: 88rpx;
			width: 88rpx;
			border-radius: 50%;
			margin-bottom: 30rpx;
			border: 1rpx solid #d0d0d0;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 44rpx;
			color: #333;
		}

		.active-xh {
			background-color: #007AFF;
			color: #ffffff;
		}

		.success {
			background: #4caf50;
			color: #fff;
		}

		.error {
			background: #f40;
			color: #fff;
		}
	}

	.text-bold {
		display: block;
		margin: 24rpx 0;
		font-size: 28rpx;
		color: #333;
		font-weight: 700;
	}

	.jx {
		margin-top: 24rpx;
	}
	.tui-mode{
		padding: 24rpx;
		.title{
			font-size: 28rpx;
			font-weight: 600;
			color: #333;
			text-align: center;
			margin-bottom: 30rpx;
		}
		.num{
			font-size: 26rpx;
			padding: 24rpx 40rpx;
		}
		.text-green{
			color: #39b54a;
		}
		.text-red{
			color:#e54d42
		}
		.text-yellow{
			color: #fbbd08;
		}
		.btn{
			margin-top: 20rpx;
			display: flex;
		}
	}
</style>